<template>
  <div class="outerBox">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>更换头像</span>
      </div>
      <div class="innerBox">
        <img
          src="../../assets/images/avatar.jpg"
          alt=""
          class="cover-img"
          ref="imgRef"
        />
        <input
          type="file"
          style="display: none"
          accept="image/*"
          ref="iptFileRef"
          @change="onCoverChangeFn"
        />
        <br />
        <el-button type="text" @click="chooseImgFn">+ 选择头像</el-button>
        <br>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import pubsub from 'pubsub-js'
import { changeUserPic } from '@/api'
import defaultImg from '@/assets/images/avatar.jpg'

export default {
  name: 'change-user-pic',
  data () {
    return {
      dialogImageUrl: ''
    }
  },
  methods: {
    chooseImgFn () {
      this.$refs.iptFileRef.click()
    },
    // 封面选择改变的事件
    onCoverChangeFn (e) {
      // 获取用户选择的文件列表
      const files = e.target.files
      if (files.length === 0) {
        // 用户没有选择封面
        this.dialogImageUrl = null
        this.$refs.imgRef.setAttribute('src', defaultImg)
      } else {
        // 用户选择了封面
        const reader = new FileReader()
        reader.readAsDataURL(files[0])
        reader.onload = () => {
          this.dialogImageUrl = reader.result
        }
        reader.onerror = () => {
          this.$message.error('选择图片失败')
        }
        const url = URL.createObjectURL(files[0])
        this.$refs.imgRef.setAttribute('src', url)
      }
    },
    async submitUpload () {
      const data = {
        avatar: this.dialogImageUrl
      }
      const res = await changeUserPic(data)
      if (res.data.code === 0) {
        this.$message.success('上传成功')
        pubsub.publish('changePic', this.dialogImageUrl)
      } else if (res.data.code === 2) {
        if (res.data.message === '"avatar" is not allowed to be empty') {
          this.$message.error('图片不能为空')
        } else {
          this.$message.error('图片过大')
        }
      }
    }
  }
}
</script>

<style scoped>

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}

.box-card {
  width: 98%;
  margin: 20px;
  height: 700px;
}

.outerBox{
  width: 100%;
  height: 500px;
}

.innerBox{
  width: 178px;
  height: 178px;
}
.cover-img{
  width: 250px;
  height: 300px;
}
.el-button{
  position: relative;
  left: 20px;
}
</style>
